require 'rubygems'
require 'hpricot'

# = IeSelectWidthFixer
#
# class used to create select boxes with corrected js for use on ie
class IeSelectWidthFixer
  public
  # filter the body of a response
  #
  # use this method in an after_filter. 
  # Example:
  #
  #   after_filter :tidy
  #   def tidy
  #     RailsTidy.filter(response)
  #   end
  def self.fix(response)
    @html = response.body
    response.body = self.fix_ie_widths
  end

  private
  def self.fix_ie_widths
    @html = self.add_js
    @html = self.add_vars_js
    @html = self.add_select_spans
    return @html
  end
  
  # Add ie select width fixer js to the end of the <head>
  def self.add_js
    return @html.gsub(/<\/head>/, 
    '<script type="text/javascript" src="/javascripts/ie_select/yahoo_2.0.0-b3.js"></script>
    <script type="text/javascript" src="/javascripts/ie_select/event_2.0.0-b3.js" ></script>
    <script type="text/javascript" src="/javascripts/ie_select/dom_2.0.2-b3.js" ></script>
    <script type="text/javascript" src="/javascripts/ie_select/ie-select-width-fix.js" ></script>
    </head>')
  end
  
  def self.add_vars_js
    selects = self.find_selects
    selects.each_with_index do |select,index|
      @html.gsub!(/<\/head>/, 
      "<script type=\"text/javascript\">
        var s#{index} = new YAHOO.Hack.FixIESelectWidth( '#{select}' );
      </script>
      </head>")
    end
    return @html
  end
  
  def self.add_select_spans
    return @html.gsub(/<select[^>]+?>.+?<\/select>/m, "<span class=\"select-box\">\\0</span>")
  end
  
  def self.find_selects
    doc = Hpricot(@html)
    doc = doc.search("//select")
    selects = []
    doc.each do |select|
      selects << select.attributes['id']
    end
    return selects
  end
end